#include "../inc/hart_slave_frame.h"

hart_device_attribute_t hart_device_attribute; // 设备属性
const uint32_t invalid_value = HART_INVALID_VALUE;
// 无效的设备变量
hart_device_variable_t hart_device_variable_invalid = {
    .code = DEVICE_VARIABLE_CODE_250,
    .classification = DEVICE_VARIABLE_CLASSIFICATION_CODE_0,
    .units_code = 0,
    .value = (float32 *)&invalid_value,
    .status = {
        .bits.device_family_specific_status = 0,
        .bits.more_device_variable_status_available = 0,
        .bits.limit_status = DEVICE_VARIABLE_STATUS_CONSTANT,
        .bits.process_data_status = DEVICE_VARIABLE_STATUS_BAD,
    },
};

/**
 * @brief 设备初始化、设备状态也设置完成后，调用改接口更新crc字段记录附加设备状态初始值
 * @return {*}
 */
void hart_additional_device_status_crc_init(void)
{
    hart_device_attribute.device_status.additional_device_status_crc = crc16_compute((uint8_t *)&hart_device_attribute.device_status.additional_device_status, sizeof(additional_device_status_t));
}

// 获取当前模块正在使用的协议版本号
uint8_t hart_get_current_protocol_version(void)
{
    return *hart_device_attribute.hart_protocol_version;
}

/**
 * @brief 获取设备变量
 * @param {uint8_t} code 设备变量编码
 * @return {*}
 */
hart_device_variable_t *get_device_variable(uint8_t code)
{
    hart_device_variable_t *hart_device_variable_p = hart_device_attribute.flash_variable.device_variable;
    for (uint8_t i = 0; i < HART_DEVICE_VARIABLE_LEN; i++)
    {
        if (hart_device_variable_p->code == code)
        {
            return hart_device_variable_p;
        }
        hart_device_variable_p++;
    }
    return &hart_device_variable_invalid;
}

/**
 * @brief 获取模拟通道
 * @param {analog_channel_number_codes_e} code
 * @return {*}
 */
analog_channel_t *get_analog_channel(analog_channel_number_codes_e code)
{
    analog_channel_t *analog_channel = hart_device_attribute.flash_variable.analog_channel;
    for (uint8_t i = 0; i < HART_ANALOG_CHANNEL_LEN; i++)
    {
        if (analog_channel->code == code)
        {
            return analog_channel;
        }
        analog_channel++;
    }
    return NULL;
}

/**
 * @brief 获取设备的地址
 * @param {uint8_t} address_type 短帧地址1个字节，长帧地址5个字节，上位机发送时从低位到高位填充，例如短地址：0x01，长地址：0x00 0x00 0x00 0x00 0x01
 * @param {uint8_t} *address    设备地址
 * @param {uint8_t} *len  设备地址长度
 * @return {*}
 */
void get_address(uint8_t address_type, uint8_t *address, uint8_t *len)
{
    if (address_type == HART_DELIMITER_TYPE_SHORT)
    {
        *len = HART_SHORT_ADDRESS_LEN;
        address[0] = hart_device_attribute.flash_variable.poll_address;
    }
    else
    {
        *len = HART_LONG_ADDRESS_LEN;
        osel_memcpy(address, hart_device_attribute.flash_variable.long_address, HART_LONG_ADDRESS_LEN);
    }
}
